package com.cookie.meetproject.ui;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;

import com.cookie.framework.adapter.CommonAdapter;
import com.cookie.framework.adapter.CommonViewHolder;
import com.cookie.framework.base.BaseBackActivity;
import com.cookie.framework.bmob.BmobManger;
import com.cookie.framework.bmob.IMUser;
import com.cookie.framework.bmob.PrivateSet;
import com.cookie.framework.utils.CommonUtils;
import com.cookie.meetproject.R;
import com.cookie.meetproject.adapter.AddFriendAdapter;
import com.cookie.meetproject.model.AddFriendModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ContactFriendActivity extends BaseBackActivity {

    private RecyclerView contactView;
    private Map<String, String> map = new HashMap<>();
    private List<AddFriendModel> mList = new ArrayList<>();
    private CommonAdapter<AddFriendModel> addFriendAdapter;
    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_firend);
        initView();
    }

    private void initView() {
        contactView = (RecyclerView) findViewById(R.id.contact_view);
        contactView.setLayoutManager(new LinearLayoutManager(this));
        contactView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        // addFriendAdapter = new AddFriendAdapter(this, mList);
        addFriendAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<AddFriendModel>() {
            @Override
            public void onBindViewHolder(final AddFriendModel model, CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setImageUrl(ContactFriendActivity.this, R.id.iv_photo, model.getPhoto());
                viewHolder.setImageResource(R.id.iv_sex, model.isSex() ? R.drawable.img_boy_icon
                        : R.drawable.img_girl_icon);
                viewHolder.setText(R.id.tv_nickname, model.getNickName());
                viewHolder.setText(R.id.tv_age, model.getAge() + "岁");
                viewHolder.setText(R.id.tv_desc, model.getDesc());
                if (model.isContact()) {
                    viewHolder.getView(R.id.ll_contact_info).setVisibility(View.VISIBLE);
                    viewHolder.setText(R.id.tv_contact_name, model.getContactName());
                    viewHolder.setText(R.id.tv_contact_phone, model.getContactPhone());
                }

                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UserInfoActivity.startActivity(ContactFriendActivity.this, model.getUserId());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_search_user_item;
            }
        });
        contactView.setAdapter(addFriendAdapter);
        loadContact();
        loadUser();
    }

    //加载用户
    private void loadUser() {

        disposable = Observable.create(new ObservableOnSubscribe<List<PrivateSet>>() {
            @Override
            public void subscribe(ObservableEmitter<List<PrivateSet>> emitter) throws Exception {
                //查询privateset
                BmobManger.getInstance().queryPrivateSet(new FindListener<PrivateSet>() {
                    @Override
                    public void done(List<PrivateSet> list, BmobException e) {
                        if (e == null) {
                            emitter.onNext(list);
                            emitter.onComplete();
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::fixPrivateSets);
    }

    //解析私有库的内容进行联系人过滤
    private void fixPrivateSets(List<PrivateSet> privateSets) {

        List<String> userListPhone = new ArrayList<>();

        for (int i = 0; i < privateSets.size(); i++) {
            PrivateSet set = privateSets.get(i);
            String phone = set.getPhone();
            userListPhone.add(phone);
        }
        //拿到所有字段的电话号码

        if (map.size() > 0) {
            for (final Map.Entry<String, String> entry : map.entrySet()) {

                //过滤：判断你当前的号码在私有库是否存在
                if (userListPhone.contains(entry.getValue())){
                    return;
                }
                BmobManger.getInstance().queryPhoneUser(entry.getValue(), new FindListener<IMUser>() {
                    @Override
                    public void done(List<IMUser> list, BmobException e) {
                        if (e == null) {
                            if (CommonUtils.isEmpty(list)) {
                                IMUser imUser = list.get(0);
                                addContent(imUser, entry.getKey(), entry.getValue());
                            }
                        }
                    }
                });
            }
        }
    }

    //加载联系人
    private void loadContact() {
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                , null, null, null, null);
        String name;
        String phone;
        while (cursor.moveToNext()) {
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            phone = phone.replace(" ", "").replace("-", "");
            map.put(name, phone);
        }
    }

    //添加内容
    private void addContent(IMUser imUser, String name, String phone) {
        AddFriendModel model = new AddFriendModel();
        model.setType(AddFriendAdapter.TYPE_CONTENT);
        model.setUserId(imUser.getObjectId());
        model.setPhoto(imUser.getPhoto());
        model.setSex(imUser.isSex());
        model.setAge(imUser.getAge());
        model.setNickName(imUser.getNickName());
        model.setDesc(imUser.getDesc());
        model.setContact(true);
        model.setContactName(name);
        model.setContactPhone(phone);
        mList.add(model);
        addFriendAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            if (disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }
}
